/**
 * Created by yiihua-013 on 16/10/26.
 *
 * 初始化,将1000个key散落在5个节点上
 */
'use strict'

const util = require('util')

var Memcached = require('memcached')

require('json-comments')

const cfg      = require('./memcached')
const nodes    = cfg.nodes
const strategy = cfg.distribute_strategy

const Mod  = require('./Mod')
const Hash = require('./ConsistentHash')

var diser = strategy === 'mod' ? new Mod() : new Hash()

// add servers
for (let nodeName in nodes) {
    diser.addNode(nodeName)
}

var clientsPool = {
    'a': new Memcached(`${nodes['a'].host}:${nodes['a'].port}`),
    'b': new Memcached(`${nodes['b'].host}:${nodes['b'].port}`),
    'c': new Memcached(`${nodes['c'].host}:${nodes['c'].port}`),
    'd': new Memcached(`${nodes['d'].host}:${nodes['d'].port}`),
    'e': new Memcached(`${nodes['e'].host}:${nodes['e'].port}`)
};

for (let i = 0; i < cfg.cnt; i++) {
    let key     = `${cfg.keyPrefix}${i}`;
    let value   = `TEST_MEM_VALUE_${i}`;
    let srvName = diser.lookup(key);
    let client  = clientsPool[srvName];
    client.set(key, value, 0, (err, success) => {
        if (err) console.error(err)
        if (success) {
            console.log(key, '初始化成功')
        }
    });
}
